package com.amokgames.tictactoe;


import java.io.IOException;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TicTacToe extends Activity implements MessageSender
//implements ComponentCallbacks
{

	private static final int REQUEST_CONNECT_DEVICE = 1;
	public static String EXTRA_DEVICE_ADDRESS = "device_address";
	private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
	GameEngine gameEngine = new GameEngine(this);
	Piece pieceButtons[][] = new Piece[3][3];

	private Button bStartClient;
	private Button bStopClient;
	private EditText etServiceName;
	private BluetoothSocket btSocket;

	private BluetoothTTTService mTTTService = null;
	
	private Turn oponent = null;

	//	@Override
	//	public void onConfigurationChanged(Configuration newConfig)
	//	{
	////		GameEngine gameEngine = this.gameEngine;
	////
	//	super.onConfigurationChanged(newConfig);
	//		//setContentView(R.layout.mainh);
	////		
	////		this.gameEngine = gameEngine;
	//	}

	@Override
	protected void onSaveInstanceState (Bundle outState) {
		super.onSaveInstanceState(outState);

		//		outState.putInt("Turn", 1);
		outState.putString("Turn", gameEngine.turn.name());

		for(Integer y = 0; y < 3; y++) {
			for(Integer x = 0; x < 3; x++) {
				outState.putString("Piece" + x.toString() + y.toString(), gameEngine.board[x][y].name());
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		bStartClient = getView(R.id.button_start_bt);
		bStartClient.setOnClickListener(new OnClickListener() {
			public void onClick(View button) {
				Intent intent= new Intent(BTClient.START);
				intent.putExtra(BTClient.EXTRA_SERVICE_NAME, "Foo");
				startService(intent);
			}
		});
		bStopClient = getView(R.id.button_stop_bt);
		bStopClient.setOnClickListener(new OnClickListener() {
			public void onClick(View button) {
				Intent intent= new Intent(BTClient.STOP);
				stopService(intent);
			}
		});


		pieceButtons[0][0] = (Piece)findViewById(R.id.tlPiece);
		pieceButtons[0][1] = (Piece)findViewById(R.id.tcPiece);
		pieceButtons[0][2] = (Piece)findViewById(R.id.trPiece);
		pieceButtons[1][0] = (Piece)findViewById(R.id.mlPiece);
		pieceButtons[1][1] = (Piece)findViewById(R.id.mcPiece);
		pieceButtons[1][2] = (Piece)findViewById(R.id.mrPiece);
		pieceButtons[2][0] = (Piece)findViewById(R.id.blPiece);
		pieceButtons[2][1] = (Piece)findViewById(R.id.bcPiece);
		pieceButtons[2][2] = (Piece)findViewById(R.id.brPiece);

		for(int y = 0; y < 3; y++)
			for(int x = 0; x < 3; x++)
				pieceButtons[x][y].setup(this, gameEngine, x, y);

		Button b = (Button)findViewById(R.id.resetButton);
		b.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				reset();
			}
		});

		if(savedInstanceState != null) {
			gameEngine.turn = Turn.valueOf(savedInstanceState.getString("Turn"));
			for(Integer y = 0; y < 3; y++) {
				for(Integer x = 0; x < 3; x++) {
					gameEngine.board[x][y] = Turn.valueOf(savedInstanceState.getString("Piece" + x.toString() + y.toString()));
				}
			}
			updateMessage();
		}
		else
			reset();

		Intent serverIntent = new Intent(this, DeviceListActivity.class);
		startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
	}

	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			TextView tv = getView(R.id.textView);
			
			switch (msg.what) {

			case BluetoothTTTService.MESSAGE_STATE_CHANGE:

				switch (msg.arg1) {
				case BluetoothTTTService.STATE_CONNECTED:
					//					mTitle.setText(R.string.title_connected_to);
					//					mTitle.append(mConnectedDeviceName);
					tv.append("Device Connected");
					//mConversationArrayAdapter.clear();
					break;
				case BluetoothTTTService.STATE_CONNECTING:
					//mTitle.setText(R.string.title_connecting);
					tv.append(getApplication().getString(R.string.title_other_devices));
					break;
				case BluetoothTTTService.STATE_LISTEN:
				case BluetoothTTTService.STATE_NONE:
					//mTitle.setText(R.string.title_not_connected);
					break;
				}
				break;
			case BluetoothTTTService.MESSAGE_WRITE:
				byte[] writeBuf = (byte[]) msg.obj;
				// construct a string from the buffer
				String writeMessage = new String(writeBuf);
				tv.append(writeMessage);
				//mConversationArrayAdapter.add("Me:  " + writeMessage);
				break;
			case BluetoothTTTService.MESSAGE_READ:
				byte[] readBuf = (byte[]) msg.obj;
				// construct a string from the valid bytes in the buffer
				String readMessage = new String(readBuf, 0, msg.arg1);
				tv.append("ReadMessage = " + readMessage);
				String[] data = readMessage.split(":");
				gameEngine.handleClick(Integer.valueOf(data[0]), Integer.valueOf(data[1]));
				refreshButtons();
				//mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
				break;
			case BluetoothTTTService.MESSAGE_DEVICE_NAME:
				// save the connected device's name
				//				mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
				//				Toast.makeText(getApplicationContext(), "Connected to "
				//						+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
				break;
			case BluetoothTTTService.MESSAGE_TOAST:
				//				Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
				//						Toast.LENGTH_SHORT).show();
				break;
			}
		}

	};
	
	private void refreshButtons() {
		for(int y = 0; y < 3; y++)
			for(int x = 0; x < 3; x++)
				pieceButtons[x][y].reset();
	}
	

	public void onStart() {
		super.onStart();

		mTTTService = new BluetoothTTTService(this, mHandler);
	}


	public void reset() {
		gameEngine.reset();
		refreshButtons();

		//updateMessage();
	}

	public void updateMessage() {
		TextView tv = (TextView)findViewById(R.id.textView);

		if(gameEngine.gameOver()) {
			if(gameEngine.didPlayerWin(Turn.x))
				tv.setText("Player X won!");
			else if(gameEngine.didPlayerWin(Turn.o))
				tv.setText("Player O won!");
			else
				tv.setText("Cat's game!");
		}
		else {
			if(gameEngine.getTurn() == Turn.x)
				tv.setText("Player X's turn");
			else if(gameEngine.getTurn() == Turn.o)
				tv.setText("Player O's turn");
		}

		tv.invalidate();
	}

	@SuppressWarnings("unchecked")
	private <T extends View> T getView(int id) {

		return (T) findViewById(id);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		String address = data.getExtras().getString(EXTRA_DEVICE_ADDRESS);
		Log.i("FooBar", data.getExtras().getString(EXTRA_DEVICE_ADDRESS));
		BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
		BluetoothDevice btv = bta.getRemoteDevice(address);
		
		if(bta.getAddress().compareTo(address) < 0) {
			oponent = Turn.o;
		}
		else {
			oponent = Turn.x;
		}

		//		try {
		//
		//			btSocket = btv.createRfcommSocketToServiceRecord(MY_UUID);
		//		} catch (IOException e) {
		//			// TODO Auto-generated catch block
		//			e.printStackTrace();
		//	
		//		}

		mTTTService.connect(btv);

		//        if(D) Log.d(TAG, "onActivityResult " + resultCode);
		//        switch (requestCode) {
		//        case REQUEST_CONNECT_DEVICE:
		//            // When DeviceListActivity returns with a device to connect
		//            if (resultCode == Activity.RESULT_OK) {
		//                // Get the device MAC address
		//                String address = data.getExtras()
		//                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
		//                // Get the BLuetoothDevice object
		//                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		//                // Attempt to connect to the device
		//                mChatService.connect(device);
		//            }
		//            break;
		//        case REQUEST_ENABLE_BT:
		//            // When the request to enable Bluetooth returns
		//            if (resultCode == Activity.RESULT_OK) {
		//                // Bluetooth is now enabled, so set up a chat session
		//                setupChat();
		//            } else {
		//                // User did not enable Bluetooth or an error occured
		//                Log.d(TAG, "BT not enabled");
		//                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
		//                finish();
		//            }
		//        }
	}

	@Override
	public void send(String message) {

		mTTTService.write(message.getBytes());

	}

}